{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 10.1处理登录表单"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 10.1.1\t处理登录表单"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "200\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "session = requests.session()\n",
    "\n",
    "post_url = 'http://www.santostang.com/wp-login.php'\n",
    "agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'\n",
    "headers = {\n",
    "    \"Host\": \"www.santostang.com\",\n",
    "    \"Origin\":\"http://www.santostang.com\",\n",
    "    \"Referer\":\"http://www.santostang.com/wp-login.php\",\n",
    "    'User-Agent': agent\n",
    "}\n",
    "postdata = {\n",
    "    'pwd': 'a12345',\n",
    "    'log': 'test',\n",
    "    'rememberme' : 'forever',\n",
    "    'redirect_to': 'http://www.santostang.com/wp-admin/',\n",
    "    'testcookie' : 1,\n",
    "}\n",
    "\n",
    "login_page = session.post(post_url, data=postdata, headers=headers)\n",
    "print(login_page.status_code)\n",
    "session.cookies.save()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## 10.1.2\t处理cookies，让网页记得你的登录"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "import http.cookiejar as cookielib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "session = requests.session()\n",
    "session.cookies = cookielib.LWPCookieJar(filename='cookies')\n",
    "try:\n",
    "    session.cookies.load(ignore_discard=True)\n",
    "except:\n",
    "print(\"Cookie 未能加载\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def isLogin():\n",
    "    url = \"http://www.santostang.com/wp-admin/profile.php\"\n",
    "    login_code = session.get(url, headers=headers, allow_redirects=False).status_code\n",
    "    if login_code == 200:\n",
    "        return True\n",
    "    else:\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "if __name__ == '__main__':\n",
    "    agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'\n",
    "    headers = {\n",
    "        \"Host\": \"www.santostang.com\",\n",
    "        \"Origin\":\"http://www.santostang.com\",\n",
    "        \"Referer\":\"http://www.santostang.com/wp-login.php\",\n",
    "        'User-Agent': agent\n",
    "    }\n",
    "    if isLogin():\n",
    "        print('您已经登录')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 10.1.3\t完整的登录代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cookie 未能加载\n",
      "200\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import http.cookiejar as cookielib\n",
    "\n",
    "session = requests.session()\n",
    "session.cookies = cookielib.LWPCookieJar(filename='cookies')\n",
    "try:\n",
    "    session.cookies.load(ignore_discard=True)\n",
    "except:\n",
    "    print(\"Cookie 未能加载\")\n",
    "\n",
    "def isLogin():\n",
    "    # 通过查看用户个人信息来判断是否已经登录\n",
    "    url = \"http://www.santostang.com/wp-admin/profile.php\"\n",
    "    login_code = session.get(url, headers=headers, allow_redirects=False).status_code\n",
    "    if login_code == 200:\n",
    "        return True\n",
    "    else:\n",
    "        return False\n",
    "    \n",
    "def login(secret, account):\n",
    "    post_url = 'http://www.santostang.com/wp-login.php'\n",
    "    postdata = {\n",
    "        'pwd': secret,\n",
    "        'log': account,\n",
    "        'rememberme' : 'true',\n",
    "        'redirect_to': 'http://www.santostang.com/wp-admin/',\n",
    "        'testcookie' : 1,\n",
    "    }\n",
    "    try:\n",
    "        # 不需要验证码直接登录成功\n",
    "        login_page = session.post(post_url, data=postdata, headers=headers)\n",
    "        login_code = login_page.text\n",
    "        print(login_page.status_code)\n",
    "        #print(login_code)\n",
    "    except:\n",
    "        pass\n",
    "    session.cookies.save()\n",
    "    \n",
    "if __name__ == '__main__':\n",
    "    agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'\n",
    "    headers = {\n",
    "        \"Host\": \"www.santostang.com\",\n",
    "        \"Origin\":\"http://www.santostang.com\",\n",
    "        \"Referer\":\"http://www.santostang.com/wp-login.php\",\n",
    "        'User-Agent': agent\n",
    "    }\n",
    "    if isLogin():\n",
    "        print('您已经登录') \n",
    "    else:\n",
    "        login('a12345', 'test') "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# 10.2验证码的处理"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 10.2.2\t人工方法处理验证码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def get_si_code():\n",
    "    # si_code 是一个动态变化的参数\n",
    "    index_url = 'http://www.santostang.com/wp-login.php?action=register'\n",
    "    # 获取注册时需要用到的 si_code\n",
    "    index_page = session.get(index_url, headers=headers)\n",
    "    html = index_page.text\n",
    "    pattern = r'name=\"si_code_reg\" type=\"hidden\"  value=\"(.*?)\"'\n",
    "    # 这里用re.search方法找到si_code\n",
    "    si_code = re.search(pattern, html).group(1)\n",
    "    return si_code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def get_captcha(si_code):\n",
    "    captcha_url = \"http://www.santostang.com/wp-content/plugins/si-captcha-for-wordpress/captcha/securimage_show.php?si_sm_captcha=1&si_form_id=reg\" + si_code\n",
    "    r = session.get(captcha_url, headers=headers)\n",
    "    with open('captcha.jpg', 'wb') as f:\n",
    "        f.write(r.content)\n",
    "        f.close()\n",
    "    try:\n",
    "        im = Image.open('captcha.jpg')\n",
    "        im.show()\n",
    "        im.close()\n",
    "    except:\n",
    "        print(u'请到 %s 目录找到captcha.jpg 手动输入' % os.path.abspath('captcha.jpg'))\n",
    "    captcha = input(\"please input the captcha\\n>\")\n",
    "    return captcha"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def register(account, email,si_code):      \n",
    "    post_url = 'http://www.santostang.com/wp-login.php?action=register'\n",
    "    postdata = {\n",
    "        'user_login': account,\n",
    "        'user_email': email,\n",
    "        'si_code_reg': si_code,\n",
    "        'redirect_to': '',\n",
    "        }\n",
    "    # 调用get_captcha函数，获取验证码数字\n",
    "    postdata[\"captcha\"] = get_captcha(si_code)  \n",
    "    # 提交POST请求，进行注册\n",
    "    register_page = session.post(post_url, data=postdata, headers=headers)\n",
    "    # 若输出打印结果为200，则表示注册成功\n",
    "    print(register_page.status_code)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "please input the captcha\n",
      ">3p5e\n",
      "200\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import re\n",
    "import os\n",
    "from PIL import Image\n",
    "if __name__ == '__main__':\n",
    "    agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'\n",
    "    headers = {\n",
    "        \"Host\": \"www.santostang.com\",\n",
    "        \"Origin\":\"http://www.santostang.com\",\n",
    "        \"Referer\":\"http://www.santostang.com/wp-login.php\",\n",
    "        'User-Agent': agent\n",
    "    }\n",
    "    session = requests.session()\n",
    "    #获取我们需要的验证码匹配码\n",
    "    si_code = get_si_code()\n",
    "    # 调用注册函数进行注册\n",
    "    account = '18341432113'\n",
    "    email = 'a12345@qq.com'\n",
    "    register(account, email, si_code)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 10.2.3\tOCR处理验证码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from PIL import Image\n",
    "im = Image.open('captcha.jpg')\n",
    "gray = im.convert('L')\n",
    "gray.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "gray.save(\"captcha_gray.jpg\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "threshold = 150\n",
    "table = []\n",
    "for i in range(256):\n",
    "    if i < threshold:\n",
    "        table.append(0)\n",
    "    else:\n",
    "        table.append(1)\n",
    "out = gray.point(table, '1')\n",
    "out.show()\n",
    "out.save(\"captcha_thresholded.jpg\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3P5E\n"
     ]
    }
   ],
   "source": [
    "import pytesseract\n",
    "th = Image.open('captcha_thresholded.jpg')\n",
    "print(pytesseract.image_to_string(th))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import pytesseract"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
